package com.alipay.gradledemo;

import android.os.AsyncTask;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @name： SportInspect
 * @author： lion
 * @time： 2023/7/13 15:57
 * @version： 1.0
 * @description：
 */
public class NetworkSpeedTest {
    public static void startDownLoadSpeed() {
        new AsyncTask<Integer, Integer, Integer>() {

            @Override
            protected Integer doInBackground(Integer... integers) {
                // 在其他类中调用downloadSpeed()方法
                double speed = NetworkSpeedTest.downloadSpeed("http://222.92.99.46:4661/health/20230706/admin/vinno_checkbody_null_1_1688663153899.apk");
                if (speed > 0) {
                    System.out.println("speed==>下载速度为：" + speed + " MB/s" + "  " + speed * 8 + "Mbps" + "  " + speed * 1024 + "kb/s");
                } else {
                    System.out.println("speed==>无法测试下载速度");
                }
                return null;
            }
        }.execute(0);
    }

    public static void startUploadSpeed() {
        new AsyncTask<Integer, Integer, Integer>() {

            @Override
            protected Integer doInBackground(Integer... integers) {
                // 在其他类中调用downloadSpeed()方法
//                double speed = NetworkSpeedTest.uploadSpeed("http://222.92.99.46:4661/api/common/singleupload",  100 * 1024);
//                if (speed > 0) {
//                    System.out.println("speed==>上传速度为：" + speed + " MB/s" + "  " + speed * 8 + "Mbps" + "  " + speed * 1024 + "kb/s");
//                } else {
//                    System.out.println("speed==>无法测试上传速度");
//                }
                try {
                    Map<String, String> requestParamsMap = new HashMap<String, String>();
                    requestParamsMap.put("alias", "health");
//                    Map<String, byte[]> files = new HashMap<String, byte[]>();
//                    byte[] bytes = getContent("/sdcard/DCIM/health_pad_v1.0.7_2023-01-06_.apk");
//                    files.put("file", bytes);
//                    String b = postFile("http://222.92.99.46:4661/api/common/singleupload", requestParamsMap, files);
//                    System.out.println("speed====>" + b);

                    Map<String, File> files = new HashMap<String, File>();
                    File file = new File("/sdcard/DCIM/health_pad_v1.0.7_2023-01-06_.apk");
                    files.put("file", file);
                    String b = post("http://222.92.99.46:4661/api/common/singleupload", requestParamsMap, files);
                    System.out.println("speed====>"+b);
                } catch (Exception e) {
                    System.out.println("speed====>" + e.toString());
                    e.printStackTrace();
                }
                return null;
            }
        }.execute(0);

    }

    //下载速度代码
    public static double downloadSpeed(String url) {
        try {
            URLConnection connection = new URL(url).openConnection();
            long startTime = System.currentTimeMillis();
            System.out.println("speed==>startTime:" + startTime);
            InputStream stream = new BufferedInputStream(connection.getInputStream());
            byte[] buffer = new byte[1024];
            int bytesRead = 0;
            while ((bytesRead = stream.read(buffer)) != -1) {
                // 读取数据，但不做任何事情
            }
            long endTime = System.currentTimeMillis();
            System.out.println("speed==>endTime:" + endTime);
            double downloadTime = (endTime - startTime) / 1000.0;
            double downloadSpeed = connection.getContentLength() / downloadTime / 1024 / 1024;
            return downloadSpeed;
        } catch (Exception e) {
            return -1;
        } finally {

        }
    }

    //上传速度代码
    public static double uploadSpeed(String url, int fileSize) {
        try {
            System.out.println("speed==>start upload");
            long startTime = System.currentTimeMillis();
            System.out.println("speed==>startTime:" + startTime);
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
            byte[] data = new byte[fileSize];
            outputStream.write(data);
            outputStream.flush();
            outputStream.close();
            InputStream stream = connection.getInputStream();
            byte[] buffer = new byte[1024];
            int bytesRead = 0;
            while ((bytesRead = stream.read(buffer)) != -1) {
                // 读取数据，但不做任何事情
            }
            long endTime = System.currentTimeMillis();
            System.out.println("speed==>endTime:" + endTime);
            double uploadTime = (endTime - startTime) / 1000.0;
            double uploadSpeed = fileSize / uploadTime / 1024 / 1024;
            return uploadSpeed;
        } catch (Exception e) {
            return -1;
        }
    }

    /**
     * 通过拼接的方式构造请求内容，实现参数传输以及文件传输
     *
     * @param actionUrl 访问的服务器URL
     * @param params    普通参数
     * @param files     文件参数
     * @return
     * @throws IOException
     */
    public static String post(String actionUrl, Map<String, String> params,
                              Map<String, File> files) throws Exception {

        StringBuilder sb2 = new StringBuilder();
        String BOUNDARY = java.util.UUID.randomUUID().toString();
        String PREFIX = "----", LINEND = "\r\n";
        String MULTIPART_FROM_DATA = "multipart/form-data";
        String CHARSET = "UTF-8";

        URL uri = new URL(actionUrl);
        HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
        conn.setReadTimeout(5 * 1000); // 缓存的最长时间
        conn.setDoInput(true);// 允许输入
        conn.setDoOutput(true);// 允许输出
        conn.setUseCaches(false); // 不允许使用缓存
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "keep-alive");
        conn.setRequestProperty("Accept", "application/json, text/plain, */*");
        conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
        conn.setRequestProperty("Charset", "UTF-8");
        conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA
                + ";boundary=" + PREFIX + BOUNDARY);
        conn.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36");

        // 首先组拼文本类型的参数
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            sb.append(PREFIX+BOUNDARY+LINEND);
            sb.append("Content-Disposition: form-data; name=\""
                    + entry.getKey() + "\"" + LINEND);
           // sb.append("Content-Type: application/json; charset=" + CHARSET + LINEND);
           // sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
            //sb.append(LINEND);
            sb.append(entry.getValue());
            sb.append(LINEND);
        }
        //附件
        DataOutputStream outStream = new DataOutputStream(
                conn.getOutputStream());
        outStream.write(sb.toString().getBytes());
        // 发送文件数据
        if (files != null) {
            for (Map.Entry<String, File> file : files.entrySet()) {
                StringBuilder sb1 = new StringBuilder();
                sb1.append(PREFIX+BOUNDARY+LINEND);
                // name是post中传参的键 filename是文件的名称
                sb1.append("Content-Disposition: form-data; name=\"file\"; filename=\""
                        + file.getValue().getName() + "\"" + LINEND);
                sb1.append("Content-Type: application/vnd.android.package-archive");
                sb1.append(LINEND);
                System.out.println("speed==>start upload=sb1=="+sb1);
                //写入输出流
                outStream.write(sb1.toString().getBytes());

                //写入附件字节流
                InputStream is = new FileInputStream(file.getValue());
                byte[] buffer = new byte[1024];
                int len = 0;
                //一次都1024个字节
                while ((len = is.read(buffer)) != -1) {
                    outStream.write(buffer, 0, len);
                }
                is.close();
                //写入换行
                outStream.write(LINEND.getBytes());
            }

        }
        // 请求结束标志
        byte[] end_data = (PREFIX + BOUNDARY + LINEND).getBytes();
        outStream.write(end_data);
        outStream.flush();
        // 得到响应码
        int res = conn.getResponseCode();
        if (res == 200) {
            // 读取返回数据
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    conn.getInputStream(), "UTF-8")); //$NON-NLS-1$
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb2.append(line).append("\n"); //$NON-NLS-1$
            }
            reader.close();
        }
        outStream.close();
        conn.disconnect();

        return sb2.toString();
    }

    /**
     * 以数据流的形式传参
     *
     * @param actionUrl
     * @param params
     * @param files
     * @return
     * @throws Exception
     */
    public static String postFile(String actionUrl, Map<String, String> params,
                                  Map<String, byte[]> files) throws Exception {
        StringBuilder sb2 = new StringBuilder();
        String BOUNDARY = java.util.UUID.randomUUID().toString();
        String PREFIX = "--", LINEND = "\r\n";
        String MULTIPART_FROM_DATA = "multipart/form-data";
        String CHARSET = "UTF-8";

        URL uri = new URL(actionUrl);
        HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
        conn.setReadTimeout(6 * 1000); // 缓存的最长时间
        conn.setDoInput(true);// 允许输入
        conn.setDoOutput(true);// 允许输出
        conn.setUseCaches(false); // 不允许使用缓存
        conn.setRequestMethod("POST");
        conn.setRequestProperty("connection", "keep-alive");
        conn.setRequestProperty("Charsert", "UTF-8");
        conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA
                + ";boundary=" + BOUNDARY);

        // 首先组拼文本类型的参数
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            sb.append(PREFIX);
            sb.append(BOUNDARY);
            sb.append(LINEND);
            sb.append("Content-Disposition: form-data; name=\""
                    + entry.getKey() + "\"" + LINEND);
            sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
            sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
            sb.append(LINEND);
            sb.append(entry.getValue());
            sb.append(LINEND);
        }

        DataOutputStream outStream = new DataOutputStream(
                conn.getOutputStream());
        outStream.write(sb.toString().getBytes());
        InputStream in = null;
        // 发送文件数据
        if (files != null) {
            for (Map.Entry<String, byte[]> file : files.entrySet()) {
                StringBuilder sb1 = new StringBuilder();
                sb1.append(PREFIX);
                sb1.append(BOUNDARY);
                sb1.append(LINEND);

                sb1.append("Content-Disposition: form-data; name=\"file\"; filename=\"" //$NON-NLS-1$
                        + file.getKey() + "\"" + LINEND);
                sb1.append("Content-Type:" + "application/octet-stream;UTF-8"
                        + LINEND);
                sb1.append(LINEND);
                outStream.write(sb1.toString().getBytes());

                outStream.write(file.getValue());

                outStream.write(LINEND.getBytes());
            }

        }
        // 请求结束标志
        byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
        outStream.write(end_data);
        outStream.flush();
        // 得到响应码
        int res = conn.getResponseCode();
        if (res == 200) {
            // 读取返回数据
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    conn.getInputStream(), "UTF-8")); //$NON-NLS-1$
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb2.append(line).append("\n"); //$NON-NLS-1$
            }
            reader.close();
        }
        outStream.close();
        conn.disconnect();
        return sb2.toString();
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String Default_Address = "http://192.168.21.106:8080/ideweb/noSessionAndSecurity_submitBug.do";
        try {
            Map<String, String> requestParamsMap = new HashMap<String, String>();
            requestParamsMap.put("alias", "health");
            // Map<String, byte[]> files = new HashMap<String, byte[]>();
            // byte[] bytes = getContent("E:" + File.separator + "hello.txt");
            // files.put("zzz.txt", bytes);
            // String a = postFile(Default_Address, requestParamsMap, files);
            // System.out.println(a);

            Map<String, File> files = new HashMap<String, File>();
            File file = new File("/storage/sdcard0/vinno.sportinspect/fileCache/files/vinno.sportinspect.apk");
            files.put("file", file);
            String b = post(Default_Address, requestParamsMap, files);
            System.out.println(b);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static byte[] getContent(String filePath) throws IOException {
        File file = new File(filePath);
        long fileSize = file.length();
        if (fileSize > Integer.MAX_VALUE) {
            System.out.println("file too big...");
            return null;
        }
        FileInputStream fi = new FileInputStream(file);
        byte[] buffer = new byte[(int) fileSize];
        int offset = 0;
        int numRead = 0;
        while (offset < buffer.length
                && (numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0) {
            offset += numRead;
        }
        // 确保所有数据均被读取
        if (offset != buffer.length) {
            throw new IOException("Could not completely read file "
                    + file.getName());
        }
        fi.close();
        return buffer;
    }


}